package com.crr.service.impl;

import com.crr.service.OrderService;
import com.crr.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//@Service
public class OrderServiceImpl implements OrderService {

    //@Autowired
    RedisUtils redisUtils;

    @Override
    public int save(int userId, int goodsId) {

        String userKey="user:id:"+userId;
         //判断用户是否抢购过
        boolean flag=redisUtils.setNx(userKey,goodsId+"");
        if(!flag){
            //说明抢过了
            return 1;
        }
        String key = "goods:id:" + goodsId;
        //尝试扣减库存
        Long stock = redisUtils.hdecr(key,"stock");//redisUtils.decr("stock");
        if (stock < 0) {
            System.out.println("抢购失败:"+stock);
            return 0;//抢购失败
        }
        System.out.println("用户" + userId + "抢购第" + (stock + 1) + "台成功");
        //记录当前用户抢购成功
        redisUtils.set(userKey,goodsId);
        return 1;//返回抢购成功
    }

    @Override
    public void test() {
        String key = "goods:id:1";
        redisUtils.hset(key, "name", "小米");
        redisUtils.hset(key, "stock", "10");
        redisUtils.hset(key, "price", "1999");
        redisUtils.set("stock","10");
    }
}